<template>
  <div class="container">
    <div class="app-container">
      <el-tree :expand-on-click-node="false" default-expand-all :data="depts" :props="defaultProps">
        <!-- v-slot在Vue2.6开始使用,用于收集子组件slot传递的数据,这里的data就是从:data="depts"解构出来的 -->
        <template v-slot="{data}">
          <!-- 调整el-row样式,使其能横向展示 -->
          <el-row style="width: 100%;height: 40px;" type="flex" justify="space-between" align="middle">
            <el-col>{{ data.name }}</el-col>
            <!-- 每一列的:span被分为24分,代表每一列占多少比例             -->
            <el-col :span="4">
              <span class="manager">{{ data.managerName }}</span>
              <!-- 当上面数据都一样时,下拉列表只会展示一个 -->
              <el-dropdown @command="(type) => handleCommand(type, data.id)">
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
        </template>
      </el-tree>
    </div>
    <DeptDialog ref="dept" @handlerDept="getDeptsList" />
  </div>
</template>
<script>
import { getDeptsList, delDept } from '@/api/department'
import { transListToTree } from '@/utils'
import DeptDialog from './components/DeptDialog.vue'
export default {
  name: 'Department',
  components: {
    DeptDialog
  },
  data() {
    return {
      depts: [],
      // 使depts数据映射到组件
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  created() {
    this.getDeptsList()
  },
  methods: {
    async getDeptsList() {
      const res = await getDeptsList()
      this.depts = transListToTree(res, 0)
    },
    handleCommand(type, id) {
      if (type === 'add') {
        this.$refs.dept.open('新增部门', id)
      } else if (type === 'edit') {
        this.$refs.dept.open('编辑部门', id)
      } else {
        this.$confirm('您确认要删除该部门吗', '', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          await delDept(id)
          await this.getDeptsList()
          this.$message.success('删除成功')
        })
      }
    }
  }
}
</script>
<style scoped>
.app-container{
  padding: 30px 140px;
  font-size: 14px;
}
.manager{
  margin-right: 20px;
}
</style>
